/**
 * Search history clearable ComboBox
 *
 * <pre>
 *  1.listen on('search',fn(value)) event
 *  2.specify params
 *     store       Datastore
 *     paramName   Datastore baseParams property
 *     filterName  ['filter','like'] default 'like'
 * </pre>
 */
CQCIS.form.SearchBox = function(config){
    if (config.store) {
        this.ds = config.store;
        delete config.store;
    }
    CQCIS.form.SearchBox.superclass.constructor.call(this, config);
    
    this.addEvents({
        'search': true
    });
    
    this.store = new Ext.data.SimpleStore({
        fields: ['query'],
        data: []
    });
    
    this.historyRecord = Ext.data.Record.create([{
        name: 'query',
        type: 'string'
    }]);
    
    this.triggerConfig = {
        tag: 'span',
        cls: 'x-form-twin-triggers',
        style: 'padding-right:2px',
        cn: [{
            tag: "img",
            src: Ext.BLANK_IMAGE_URL,
            cls: "x-form-trigger",
            style: config.hideComboTrigger ? "display:none" : ""
        }, {
            tag: "img",
            src: Ext.BLANK_IMAGE_URL,
            cls: "x-form-trigger x-form-clear-trigger",
            style: config.hideClearTrigger ? "display:none" : ""
        }]
    };
};

Ext.extend(CQCIS.form.SearchBox, Ext.form.ComboBox, {
    store: undefined,
    displayField: 'query',
    typeAhead: false,
    mode: 'local',
    triggerAction: 'all',
    historyRecord: undefined,
    maxInHistory: 10,
    rememberOn: 'enter',
    filterName: 'like',
    paramName: 'query',
    width: 100,
    
    getTrigger: function(index){
        return this.triggers[index];
    },
    
    initTrigger: function(){
        var ts = this.trigger.select('.x-form-trigger', true);
        this.wrap.setStyle('overflow', 'hidden');
        var triggerField = this;
        ts.each(function(t, all, index){
            t.hide = function(){
                var w = triggerField.wrap.getWidth();
                this.dom.style.display = 'none';
                triggerField.el.setWidth(w - triggerField.trigger.getWidth());
            };
            t.show = function(){
                var w = triggerField.wrap.getWidth();
                this.dom.style.display = '';
                triggerField.el.setWidth(w - triggerField.trigger.getWidth());
            };
            var triggerIndex = 'Trigger' + (index + 1);
            
            if (this['hide' + triggerIndex]) {
                t.dom.style.display = 'none';
            }
            t.on("click", this['on' + triggerIndex + 'Click'], this, {
                preventDefault: true
            });
            t.addClassOnOver('x-form-trigger-over');
            t.addClassOnClick('x-form-trigger-click');
        }, this);
        this.triggers = ts.elements;
    },
    
    onTrigger1Click: function(){
        this.onTriggerClick();
    },
    onTrigger2Click: function(){
        this.clearValue();
    },
    onRender: function(ct){
        CQCIS.form.SearchBox.superclass.onRender.call(this, ct);
        this.triggers[0].hide();
        this.triggers[1].hide();
    },
    initEvents: function(){
        CQCIS.form.SearchBox.superclass.initEvents.call(this);
        
        this.el.on("keyup", this.onHistoryKeyUp.createDelegate(this));
        if (this.ds) {
            this.on('search', this.onChange.createDelegate(this));
        }
    },
    // private
    historyChange: function(value){
        var value = this.getValue().replace(/^\s+|\s+$/g, "");
        if (value.length == 0) {
            this.triggers[1].hide();
            return;
        }
        this.triggers[1].show();
        this.store.clearFilter();
        var vr_insert = true;
        if (this.rememberOn == "all") {
            this.store.each(function(r){
                if (r.data['query'].indexOf(value) == 0) {
                    // backspace
                    vr_insert = false;
                    return false;
                } else if (value.indexOf(r.data['query']) == 0) {
                    // forward typing
                    this.store.remove(r);
                }
            });
        }
        if (vr_insert == true) {
            this.store.each(function(r){
                if (r.data['query'] == value) {
                    vr_insert = false;
                }
            });
        }
        if (vr_insert == true) {
            var vr = new this.historyRecord({
                query: value
            });
            this.store.insert(0, vr);
        }
        var ss_max = this.maxInHistory;
        if (this.store.getCount() > ss_max) {
            var ssc = this.store.getCount();
            var overflow = this.store.getRange(ssc - (ssc - ss_max), ssc);
            for (var i = 0; i < overflow.length; i++) {
                this.store.remove(overflow[i]);
            }
        }
        if (this.store.getCount() > 0) {
            this.triggers[0].show();
        }
    },
    // private
    onHistoryKeyUp: function(e){
        if ((this.rememberOn == "enter" && e.getKey() == 13) || (this.rememberOn == "all")) {
            this.historyChange(this.getValue());
            this.fireEvent('search', this.getValue());
        }
    },
    // private
    onChange: function(v){
        if (this.ds) {
            var o = {
                start: 0
            };
            this.ds.baseParams = this.ds.baseParams ||
            {};
            if (v && v.length > 0) {
                this.ds.baseParams[this.filterName] = this.ds.baseParams[this.filterName] ||
                {};
                this.ds.baseParams[this.filterName][this.paramName] = v;
            } else {
                if (this.ds.baseParams[this.filterName]) {
                    delete this.ds.baseParams[this.filterName][this.paramName];
                }
            }
            this.ds.reload({
                params: o
            });
        }
    },
    /**
     * Don't trigger search event
     */
    setValue: function(v){
        if (!v || v.length == 0) {
            this.triggers[1].hide();
        }
        CQCIS.form.SearchBox.superclass.setValue.call(this, v);
    },
    /**
     * Trigger search event
     */
    clearValue: function(){
        this.setValue("");
        this.fireEvent('search', this.getValue());
    }
});
